<template>
  <van-cell title="我的帖子" center></van-cell>
  <van-list
    class="list"
    v-model="loading"
    :finished="finished"
    loading-text="加载中..."
    finished-text="没有更多了"
    offset="10"
    @load="onLoad"
  >
    <van-back-top right="3vw" bottom="12vh" />
    <van-cell-group>
      <van-cell v-for="post in list" :key="post.id">
        <van-row class="van-rowstyle">
          <van-col>
            <van-image
              round
              fit="cover"
              :src="post.useravatar"
              width="2rem"
              height="2rem"
            />
          </van-col>
          <van-col offset="1">
            <van-text-ellipsis
              class="usernamestyle"
              rows="8"
              :content="post.username"
            />
          </van-col>
        </van-row>
        <van-row class="van-rowstyle" @click="OnClickPost(post)">
          <van-col offset="3">
            <van-text-ellipsis
              class="ellstyle"
              rows="50"
              :content="post.content"
            />
          </van-col>
        </van-row>
        <van-row
          justify="space"
          @click="OnClickPost(post)"
          class="van-rowstyle"
        >
          <van-col offset="3" v-for="img in post.imagepath" :key="img">
            <van-image :src="img" fit="cover" width="6.5rem" height="6.5rem"
              ><template v-slot:error>加载失败</template></van-image
            >
          </van-col>
        </van-row>
        <van-row justify="space-between" class="van-rowstyle">
          <van-col class="tagstyle" offset="1"> #{{ post.tag }} </van-col>
          <van-col offset="1">
            {{ post.createTime }}
          </van-col>
          <van-col offset="1"> {{ post.seeNum }}人围观 </van-col>
          <van-col class="delstyle" offset="1" @click="beforeDelete(post.id)">
            删除
          </van-col>
        </van-row>
      </van-cell>
    </van-cell-group>
  </van-list>

  <van-overlay :show="showDelete" z-index="2">
    <van-popup :style="{ padding: '64px' }">
      <van-cell-group inset>
        <van-button text="确定删除" @click="DeletePost" />
        <van-button text="取消" @click="showDelete = false" />
      </van-cell-group>
    </van-popup>
  </van-overlay>
</template>

<script>
import { ref } from "vue";
import MyAxios from "@/plugins/MyAxios";
import router from "@/router";
import { showNotify } from "vant";
import store from "@/store";

export default {
  setup() {
    const backPath = ref(store.state.backedPath);
    const list = ref([]);
    const loading = ref(true);
    const finished = ref(false);
    const formatTimeDifference = (timeString) => {
      const now = new Date();
      const createTime = new Date(timeString);
      const diff = now - createTime;
      let result;

      if (diff < 0) {
        result = "未来时间";
      } else if (diff < 1000 * 60) {
        // 小于1分钟
        result = `${Math.floor(diff / 1000)} 秒前`;
      } else if (diff < 1000 * 60 * 60) {
        // 小于1小时
        result = `${Math.floor(diff / (1000 * 60))} 分钟前`;
      } else if (diff < 1000 * 60 * 60 * 24) {
        // 小于1天
        result = `${Math.floor(diff / (1000 * 60 * 60))} 小时前`;
      } else {
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        result = `${days} 天前`;
      }

      return result;
    };

    const onLoad = () => {
      if (finished.value) {
        return;
      }
      MyAxios.get("/post/getPostsByUserId")
        .then((response) => {
          response.data.forEach((postData) => {
            // 使用 forEach 替代 for 循环，并正确解构
            const {
              anon,
              anon_name,
              content,
              createTime,
              favourNum,
              id,
              isDelete,
              tags,
              thumbNum,
              title,
              updateTime,
              seeNum,
              imgpath,
            } = postData;

            let tagList = [];
            try {
              tagList = JSON.parse(tags || "[]"); // 尝试解析 tags，如果为空或不是有效 JSON，则使用空数组
            } catch (error) {
              console.error("Parsing tags failed:", error);
              tagList = []; // 解析失败时使用空数组
            }
            const tag = tagList[0] || null; // 如果没有标签，则设置为 null

            let imagePaths = [];
            try {
              imagePaths = JSON.parse(imgpath || "[]"); // 尝试解析 imgpath，同样处理空值或错误格式
            } catch (error) {
              console.error("Parsing imgpath failed:", error);
              imagePaths = []; // 解析失败时使用空数组
            }

            // 处理 imagePaths（如果需要的话）
            imagePaths = imagePaths.map(
              (path) => `http://${backPath.value}/api/postimages/${path}`
            );

            const username = ref("");
            const useravatar = ref("");
            MyAxios.get("/user/get/login").then((res) => {
              const { userAvatar, userName } = res.data;

              if (userAvatar === null || anon === 1) {
                useravatar.value = store.state.anonImg;
              } else {
                useravatar.value =
                  "http://" + backPath.value + "/api/userimages/" + userAvatar;
              }
              if (anon === 1) {
                username.value = anon_name;
              } else {
                username.value = userName;
              }
            });

            list.value.push({
              anon,
              anon_name,
              content,
              createTime: formatTimeDifference(createTime),
              favourNum,
              id,
              isDelete,
              tag,
              thumbNum,
              title,
              updateTime,
              username,
              useravatar,
              seeNum,
              imagepath: imagePaths, // 更改属性名为 imagepath 以保持一致性（如果你在其他地方也使用了这个名称）
            });
          });
          loading.value = false;
          finished.value = true;
        })
        .catch((error) => {
          console.error("Failed to load posts:", error);
          loading.value = false;
          finished.value = true; // 可能你还需要处理加载失败的情况
        });
    };

    const OnClickPost = (post) => {
      router.push({
        path: "/post", // 假设你的路由路径是 /home, /about 这样的
        query: { id: post.id },
      });
    };
    const showDelete = ref(false);
    const DeletePostId = ref(0);
    const beforeDelete = (postId) => {
      showDelete.value = true;
      DeletePostId.value = postId;
    };

    const DeletePost = () => {
      MyAxios.post("/post/delete", {
        id: DeletePostId.value,
      }).then((res) => {
        const { code, message } = res;
        if (code === 0) {
          showNotify({ type: "success", message: "删除成功" }, 500);
          setTimeout(() => {
            location.reload();
          }, 500);
        } else {
          showNotify({ type: "warning", message: message });
        }
      });
      showDelete.value = false;
    };
    return {
      list,
      loading,
      finished,
      onLoad,
      OnClickPost,
      beforeDelete,
      showDelete,
      DeletePost,
    };
  },
};
</script>

<style scoped>
.ellstyle {
  /* 调整字体大小 */
  font-size: 16px; /* 或者您想要的任何大小 */

  color: black;
  text-align: left;
  line-height: 1.6;
  /* 调整字体类型 */
  font-family: Arial, sans-serif; /* 或者您喜欢的任何字体 */
}

.usernamestyle {
  font-size: 15px;
  line-height: 1.5;
  color: #394968;
}

.tagstyle {
  font-size: 15px;
  color: #00388b;
}
/* 调整行之间的间距 */
.van-rowstyle {
  margin-bottom: 5px; /* 在每行下方添加间距 */
}
.delstyle {
  color: #00a0fd;
}
</style>
